//
//  PickerTableViewCell.m
//  CarTown
//
//  Created by xionghao on 15/8/19.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "PickerTableViewCell.h"
#import "CZCover.h"
@interface PickerTableViewCell ()<SelectClickDelegate,CZCoverDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *change;
@property (nonatomic,strong) selectView *selectview;
@property (nonatomic,strong) CZCover *cover;
@property (nonatomic,strong) NSArray *titlelist;
@property (nonatomic,weak) UITableView *tableview;
@property (nonatomic,strong) CAShapeLayer *btnlayer;
@end

@implementation PickerTableViewCell
+(instancetype)pickercellWithTableview:(UITableView *)tablview{
    PickerTableViewCell *cell=[tablview dequeueReusableCellWithIdentifier:@"picker"];
    if (cell==nil) {
        cell=[[[NSBundle mainBundle] loadNibNamed:@"PickerTableViewCell" owner:nil options:nil]lastObject];
    }
    cell.tableview=tablview;
    return cell;
}
-(void)setMode:(CarpubMode *)mode{
    _mode=mode;
    switch (mode.type) {
        case YOUHUIPOINT:
            [self.titlebtn setTitle:self.titlelist[YOUHUIPOINT] forState:UIControlStateNormal];
            break;
        case YOUHUIPRICE:
            [self.titlebtn setTitle:self.titlelist[YOUHUIPRICE] forState:UIControlStateNormal];
            break;
        case PLUSPOINT:
            [self.titlebtn setTitle:self.titlelist[PLUSPOINT] forState:UIControlStateNormal];
            break;
        case DIRESTPRICE:
            [self.titlebtn setTitle:self.titlelist[DIRESTPRICE] forState:UIControlStateNormal];
            break;
        default:
            break;
    }
    self.pointtext.text=(mode.type==YOUHUIPOINT)?@"点":@"万";
    self.textinput.text=mode.detail;
}
-(NSArray *)titlelist{
    if (_titlelist==nil) {
        _titlelist=@[@"优惠点数",@"优惠万元",@"加价万元",@"直接报价"];
    }
    return _titlelist;
}
-(void)coverDidClickCover:(CZCover *)cover{
    [self.selectview hide];
    [self animateIndicator:self.btnlayer Forward:NO];
}
-(void)awakeFromNib{
    self.textinput.delegate=self;
    
    CAShapeLayer *layer=[self createIndicatorWithColor:textnormalGary andPosition:CGPointMake(70, 22)];
    [self.titlebtn.layer addSublayer:layer];
    self.btnlayer=layer;
    [self.titlebtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    BOOL isHaveDian=NO;
    
    if (textField.keyboardType==UIKeyboardTypeDecimalPad) {
        if ([textField.text rangeOfString:@"."].location!=NSNotFound) {
            isHaveDian=YES;
        }
        if ([string length]>0)
        {
            unichar single=[string characterAtIndex:0];//当前输入的字符
            if ((single >='0' && single<='9') || single=='.')//数据格式正确
            {
                //首字母不能为0和小数点
                if([textField.text length]==0){
                    if(single == '.'){
                        [self alertView:@"亲，第一个数字不能为小数点"];
                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                        return NO;
                        
                    }
                    //                    if (single == '0') {
                    //                        [self alertView:@"亲，第一个数字不能为0"];
                    //                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    //                        return NO;
                    //
                    //                    }
                }
                if (single=='.')
                {
                    if(!isHaveDian)//text中还没有小数点
                    {
                        isHaveDian=YES;
                        return YES;
                    }else
                    {
                        [self alertView:@"亲，您已经输入过小数点了"];
                        [textField.text stringByReplacingCharactersInRange:range withString:@""];
                        return NO;
                    }
                }
                else
                {
                    if (isHaveDian)//存在小数点
                    {
                        //判断小数点的位数
                        NSRange ran=[textField.text rangeOfString:@"."];
                        int tt=range.location-ran.location;
                        int point=self.mode.type==YOUHUIPOINT?1:2;
                        if (tt <=point){
                            return YES;
                        }else{
                            [self alertView:self.mode.type==YOUHUIPOINT?@"亲，您最多输入一位小数":@"亲，您最多输入两位小数"];
                            return NO;
                        }
                    }
                    else
                    {
                        return YES;
                    }
                }
            }else{//输入的数据格式不正确
                [self alertView:@"亲，您输入的格式不正确"];
                [textField.text stringByReplacingCharactersInRange:range withString:@""];
                return NO;
            }
        }
        else
        {  
            return YES;  
        }  
        
        
        
    }else{
        return YES
        ;
    }

}
-(void)alertView:(NSString *)string{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:string delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alert show];
}

#pragma mark - animation method
- (void)animateIndicator:(CAShapeLayer *)indicator Forward:(BOOL)forward {
    [CATransaction begin];
    [CATransaction setAnimationDuration:0.25];
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithControlPoints:0.4 :0.0 :0.2 :1.0]];
    
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    anim.values = forward ? @[ @0, @(M_PI) ] : @[ @(M_PI), @0 ];
    
    if (!anim.removedOnCompletion) {
        [indicator addAnimation:anim forKey:anim.keyPath];
    } else {
        [indicator addAnimation:anim forKey:anim.keyPath];
        [indicator setValue:anim.values.lastObject forKeyPath:anim.keyPath];
    }
    
    [CATransaction commit];
    
    
}

- (CAShapeLayer *)createIndicatorWithColor:(UIColor *)color andPosition:(CGPoint)point {
    CAShapeLayer *layer = [CAShapeLayer new];
    
    UIBezierPath *path = [UIBezierPath new];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(8, 0)];
    [path addLineToPoint:CGPointMake(4, 5)];
    [path closePath];
    
    layer.path = path.CGPath;
    layer.lineWidth = 1.0;
    layer.fillColor = color.CGColor;
    
    CGPathRef bound = CGPathCreateCopyByStrokingPath(layer.path, nil, layer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, layer.miterLimit);
    layer.bounds = CGPathGetBoundingBox(bound);
    
    layer.position = point;
    
    return layer;
}


-(void)selectclick:(NSInteger)index{
    
    
    [self animateIndicator:self.btnlayer Forward:NO];
    [self.titlebtn setTitle:self.titlelist[index] forState:UIControlStateNormal];
    self.pointtext.text=index==0?@"点":@"万";
    self.mode.type=index;
    
    if ([_delegate respondsToSelector:@selector(clickWithCellTag:index:)]) {
        
        [_delegate clickWithCellTag:self index:index];
    }
    [self.cover removeFromSuperview];
    [self.selectview hide];
    if ([_delegate respondsToSelector:@selector(datachange:)]) {
        [_delegate datachange:self];
    }

}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    self.mode.detail=textField.text;
    if ([_delegate respondsToSelector:@selector(datachange:)]) {
        [_delegate datachange:self];
    }
}

- (IBAction)changeclick:(id)sender {
    [self animateIndicator:self.btnlayer Forward:YES];
    CZCover *cover=[CZCover show];
    cover.delegate=self;
    self.cover=cover;
    selectView *selectview=[selectView selectview];
    selectview.width=self.change.width+20;
    selectview.x=0;
    selectview.height=0;
   NSIndexPath *indexpath= [self.tableview indexPathForCell:self];
    
    CGRect rectInTableView = [self.tableview rectForRowAtIndexPath:indexpath];
    CGRect rect = [self.tableview convertRect:rectInTableView toView:[self.tableview superview]];
   selectview.y=CGRectGetMaxY(rect);
    [CZKeyWindow addSubview:selectview];
    selectview.delegate=self;
    [selectview showView];
    self.selectview=selectview;
    
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
